package com.andnux.android.utils;

import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterUtils {

    private static final String TAG = "DeflaterUtils";

    public static String zipString(String unzipString) {
        Log.d(TAG, "zipString() called with: unzipString = [" + unzipString + "]");
        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
        //设置压缩输入数据
        deflater.setInput(unzipString.getBytes());
        //当被调用时，表示压缩应该以输入缓冲区的当前内容结束
        deflater.finish();

        final byte[] bytes = new byte[1024];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);

        while (!deflater.finished()) {
            //压缩输入数据并用压缩数据填充指定的缓冲区
            int length = deflater.deflate(bytes);
            outputStream.write(bytes, 0, length);
        }
        //关闭压缩器并丢弃任何未处理的输入
        deflater.end();
        return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_PADDING);
    }

    /**
     * 解压缩
     */
    public static String unzipString(String zipString) {
        byte[] decode;
        try {
            decode = Base64.decode(zipString, Base64.NO_PADDING);
        } catch (IllegalArgumentException ex) {
            return null;
        }
        //创建一个解压缩器
        Inflater inflater = new Inflater();
        inflater.setInput(decode);
        final byte[] bytes = new byte[1024];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        try{
            //如果已经到压缩数据流末尾，会返回true
            while (!inflater.finished()){
                //将字节解压缩到指定的缓冲区
                int length = inflater.inflate(bytes);
                outputStream.write(bytes, 0, length);
            }
        } catch (DataFormatException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            //关闭压缩器并丢弃任何未处理的输入
            inflater.end();
        }
        return outputStream.toString();
    }
}
